//
//  BCClipGridView.m
//  图片编辑
//
//  Created by aaaa on 2020/3/25.
//  Copyright © 2020 aaaa. All rights reserved.
//

#import "BCClipGridView.h"
#import "BCClipGridLayer.h"

typedef struct RectOffsetStruct {
    CGFloat left;
    CGFloat right;
    CGFloat top;
    CGFloat bottom;
}RectOffset;

//最小的边长
static const CGFloat miniumLineWidth  = 80;
//每条边的宽度（高度）
static const CGFloat interactor_width = 25;

@interface BCClipGridView ()
//最小范围(网格最大)
@property(nonatomic,assign)CGSize miniumSize;
//最大范围(网格最小)
@property(nonatomic,assign)CGSize maxiumSize;
//初始化范围(用在)
@property(nonatomic,assign)CGRect gridRect;
//改变的范围(用在拖拽中)
@property(nonatomic,assign)CGRect changingRect;
//限制的范围
@property(nonatomic,assign)CGRect limitRect;

@property(nonatomic,strong)BCClipGridLayer *gridLayer;

@property(nonatomic,assign)CGRect leftLineRect;
@property(nonatomic,assign)CGRect rightLineRect;
@property(nonatomic,assign)CGRect bottomLineRect;
@property(nonatomic,assign)CGRect topLineRect;

@property(nonatomic,assign)BCGridLineDragDirection direction;
@property(nonatomic,strong)UIPanGestureRecognizer *pan;

@end

@implementation BCClipGridView
-(instancetype)initWithFrame:(CGRect)frame
                  originRect:(CGRect)rect
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
        _gridRect = rect;
        _changingRect = rect;
        [self initUI];
        [self setInterActorZoon];
        
        _pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
        _pan.enabled = NO;
        [self addGestureRecognizer:_pan];
    }
    return self;
}

-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    return YES;
}

//初始化
-(void)initUI{
    _miniumSize = CGSizeMake(60, 60);
    _maxiumSize = CGRectInset(self.bounds, 20, 20).size;
        
    _gridLayer = [[BCClipGridLayer alloc] initWithFrame:self.bounds];
    [_gridLayer setGridRect:_gridRect animate:NO];
    [self.layer addSublayer:_gridLayer];
}

//穿透手势
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    UIView *view = [super hitTest:point withEvent:event];
    if (![self checkTouchPointIsAvlid:point] && self == view) {
        return nil;
    }
    return self;
}

-(void)pan:(UIPanGestureRecognizer *)pan{
    
//    NSLog(@"%@",NSStringFromCGPoint([pan translationInView:self]));
    
    if (pan.state == UIGestureRecognizerStateCancelled ||
        pan.state == UIGestureRecognizerStateEnded ||
        pan.state == UIGestureRecognizerStateFailed )
    { // 结束拖拽
        _pan.enabled = NO;
        _gridRect = _changingRect;
        [self setInterActorZoon];
        
        if ([self.delegate respondsToSelector:@selector(didEndResizeGridRect:)]) {
            [self.delegate didEndResizeGridRect:_changingRect];
        }
    }else{
        CGPoint point = [pan translationInView:self];
        RectOffset offset = {0,0,0,0};
        switch (_direction) {
            case BCGridLineDragDirection_None: {
                
            } break;
            case BCGridLineDragDirection_Left: {
                offset.left = point.x;
            } break;
            case BCGridLineDragDirection_Right: {
                offset.right = point.x;
            } break;
            case BCGridLineDragDirection_Top: {
                offset.top = point.y;
            } break;
            case BCGridLineDragDirection_Bottom: {
                offset.bottom = point.y;
            } break;
            case BCGridLineDragDirection_TLCorner: {
                offset.top = point.y;
                offset.left = point.x;
            } break;
            case BCGridLineDragDirection_TRCorner: {
                offset.top = point.y;
                offset.right = point.x;
            } break;
            case BCGridLineDragDirection_BLCorner: {
                offset.bottom = point.y;
                offset.left = point.x;
            } break;
            case BCGridLineDragDirection_BRCorner: {
                offset.bottom = point.y;
                offset.right = point.x;
            } break;
            default:
                break;
        }
        //
        [self reculculateNewGridWithOffset:offset];
    }
}

-(void)updateRect:(CGRect)rect{
    _gridRect = rect;
    [self.gridLayer setGridRect:_gridRect animate:YES];
    [self setInterActorZoon];
}

-(void)updateLimitRect:(CGRect)limitRect{
    _limitRect = limitRect;
}

//
-(void)reculculateNewGridWithOffset:(RectOffset)offset{
    CGFloat min_x = CGRectGetMinX(_gridRect);
    CGFloat max_x = CGRectGetMaxX(_gridRect);
    CGFloat min_y = CGRectGetMinY(_gridRect);
    CGFloat max_y = CGRectGetMaxY(_gridRect);
    
    min_x += offset.left;
    max_x += offset.right;
    min_y += offset.top;
    max_y += offset.bottom;
    
    min_x = MAX(CGRectGetMinX(_limitRect), min_x);
    max_x = MIN(CGRectGetMaxX(_limitRect), max_x);
    min_y = MAX(CGRectGetMinY(_limitRect), min_y);
    max_y = MIN(CGRectGetMaxY(_limitRect), max_y);
    
    if ((max_x - min_x) < miniumLineWidth) {//限制最小宽度
        if (offset.right)
            max_x = min_x + miniumLineWidth;
        if (offset.left)
            min_x = max_x - miniumLineWidth;
    }
    
    if ((max_y - min_y) < miniumLineWidth) {//限制最大高度
        if (offset.bottom)
            max_y = min_y + miniumLineWidth;
        if (offset.top)
            min_y = max_y - miniumLineWidth;
    }
    
    
    
    _changingRect = CGRectMake(min_x, min_y, max_x-min_x, max_y - min_y);

    [self.gridLayer setGridRect:_changingRect animate:NO];
    [self setInterActorZoon];
    
    if ([self.delegate respondsToSelector:@selector(didBeginResizeGridRect:)]) {
        [self.delegate didBeginResizeGridRect:_changingRect];
    }
}

-(BOOL)checkTouchPointIsAvlid:(CGPoint)point{
    _direction = BCGridLineDragDirection_None;
    if (CGRectContainsPoint(_leftLineRect, point)) {
        _direction = _direction | BCGridLineDragDirection_Left;
    }
    if (CGRectContainsPoint(_topLineRect, point)){
        _direction = _direction | BCGridLineDragDirection_Top;
    }
    if (CGRectContainsPoint(_rightLineRect, point)){
        _direction = _direction | BCGridLineDragDirection_Right;
    }
    if (CGRectContainsPoint(_bottomLineRect, point)){
        _direction = _direction | BCGridLineDragDirection_Bottom;
    }
    BOOL canResize = !(_direction == BCGridLineDragDirection_None);
    _pan.enabled = canResize;
    
    if (canResize && [self.delegate respondsToSelector:@selector(willBeginResizeGridRect:)]) {
        [self.delegate willBeginResizeGridRect:_gridRect];
    }
    return _pan.enabled;
}


//添加操作范围
-(void)setInterActorZoon{
    
    CGFloat margin = interactor_width * .5;
    
    _leftLineRect = CGRectMake(_gridRect.origin.x - margin,
                               _gridRect.origin.y - margin,
                               interactor_width,
                               _gridRect.size.height + interactor_width);
    
    _rightLineRect = CGRectMake(CGRectGetMinX(_leftLineRect) + _gridRect.size.width,
                                _gridRect.origin.y - margin,
                                interactor_width,
                                _gridRect.size.height + interactor_width);
    
    _topLineRect = CGRectMake(_gridRect.origin.x - margin,
                              _gridRect.origin.y - margin,
                              _gridRect.size.width + interactor_width,
                              interactor_width);
    
    _bottomLineRect = CGRectMake(_gridRect.origin.x - margin,
                                 CGRectGetMinY(_topLineRect) + _gridRect.size.height,
                                 _gridRect.size.width + interactor_width,
                                 interactor_width);
}

@end
